import {
  createNotice,
  getNoticeAllById,
  getNotices,
  removeNoticesByIds,
  updateNotice,
  changeState,
  getPreviewNewsContent
} from '@/api/notice'

const state = {
  notices: [],
  notices_total: 0
}

const mutations = {

  SET_NOTICES(state, data) {
    state.notices = data.records
    state.notices_total = data.total
  }

}

const actions = {

  getNotices({commit} ,data) {
    return new Promise((resolve, reject) => {
      getNotices(data).then((resp) => {
        if (resp.data.code === 1) {
          commit("SET_NOTICES", resp.data.data)
          resolve(true)
        } else if (resp.data.code === 0) {
          reject(resp.data.msg)
        }
        reject("读取公告信息失败")
      }).catch((error) => {
        reject(error)
      })
    })
  },

  createNotice({commit}) {
    return new Promise((resolve, reject) => {
      createNotice().then((resp) => {
        if (resp.data.code === 1) {
          resolve(resp.data.data.id)
        } else if (resp.data.code === 0) {
          reject("公告创建失败")
        }
        reject("公告创建失败")
      }).catch((error) => {
        reject(error)
      })
    })
  },

  getNoticeAllById({commit} ,id) {
    return new Promise((resolve, reject) => {
      getNoticeAllById(id).then((resp) => {
        if (resp.data.code === 1) {
          resolve(resp.data.data)
        } else if (resp.data.code === 0) {
          reject(resp.data.msg)
        }
        reject("读取公告信息失败")
      }).catch((error) => {
        reject(error)
      })
    })
  },

  updateNotice({commit}, data) {
    return new Promise((resolve, reject) => {
      updateNotice(data).then((resp) => {
        if (resp.data.code === 1) {
          resolve(resp)
        }
        reject("error")
      }).catch((error) => {
        reject(error)
      })
    })
  },

  removeNoticesByIds({commit}, data) {
    return new Promise((resolve, reject) => {
      removeNoticesByIds(data).then((resp) => {
        if (resp.data.code === 1) {
          resolve(resp)
        }
        reject("error")
      }).catch((error) => {
        reject(error)
      })
    })
  },

  getPreviewNewsContent({commit}, id) {
    return new Promise((resolve, reject) => {
      getPreviewNewsContent(id).then((resp) => {
        if (resp.data.code === 1) {
          resolve(resp)
        }
        reject("error")
      }).catch((error) => {
        reject(error)
      })
    })
  },

  changeState({commit}, data) {
    return new Promise((resolve, reject) => {
      changeState(data).then((resp) => {
        if (resp.data.code === 1) {
          resolve(resp)
        }
        reject("error")
      }).catch((error) => {
        reject(error)
      })
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
